package com.spider.lwlk.mysql.workplace

import com.spider.lwlk.mysql.config.DBConfig
import com.spider.lwlk.mysql.task.ContractTask
import com.spider.lwlk.mysql.task.ExtendTask
import groovy.sql.Sql

class WorkPlace {

    private static r = new Random(Calendar.getInstance().getTimeInMillis())

    private taskFactory

    def WorkPlace() {

        initializeDatabase()

        initializePage()
    }

    private static initializeDatabase() {

        Sql.withInstance(DBConfig.dbArgs) { Sql db ->

            db.call("{call initialize_database()}")
        }
    }

    private static initializePage() {

        Sql.withInstance(DBConfig.dbArgs) { Sql db ->

            new File("src/main/oripage/oripage").eachLine { line ->

                if(!hasUrl(line)) db.executeInsert("insert into page_url_table(url) values(?)", [line])
            }
        }
    }

    private static hasUrl(String url) {

        boolean f1 = false, f2 = false

        Sql.withInstance(DBConfig.dbArgs) { Sql db ->

            f1 = db.firstRow("select * from page_url_check_table where url = ? limit 1", [url])

            f2 = db.firstRow("select * from page_url_table where url = ? limit 1", [url])
        }

        f1 || f2
    }

    def run() {

        if(taskFactory) while(!taskFactory.call().doGet().isCompleted()) {

            longSleep()
        }

        shortSleep()

        this
    }

    def hasNext() {

        taskFactory = [getBookOrNull(),  getPageOrNull()].find() { e -> e != null }

        taskFactory != null
    }

    private static getPageOrNull() {

        def ret = null

        Sql.withInstance(DBConfig.dbArgs) { Sql db ->

            if(db.firstRow("select count(0) as cnt from page_url_table").cnt != 0) {

                def path = db.firstRow("select * from page_url_table limit 1").url as String

                ret = { -> new ExtendTask(path: path) }
            }
        }

        ret
    }

    private static getBookOrNull() {

        def ret = null

        Sql.withInstance(DBConfig.dbArgs) { Sql db ->

            if(db.firstRow("select count(0) as cnt from book_url_table").cnt != 0) {

                def path = db.firstRow("select * from book_url_table limit 1").url as String

                ret = { -> new ContractTask(path: path) }
            }
        }

        ret
    }

    private static shortSleep() {

        Thread.sleep((r.nextInt(3) + 3) * 100)
    }

    private static longSleep() {

        Thread.sleep((r.nextInt(5) + 30) * 1000)
    }
}
